﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Pdf2ImageProcess
{
    public sealed class LocalLog
    {
        private static FileStream g_fileLog;

        private static readonly LocalLog instance = new LocalLog();
        private string realFilePath="";
        private DateTime oldDate;
        private LocalLog()
        {
            SetFilePath("");
        }

        public static LocalLog GetInstance()
        {
            return instance;
        }
        public void SetFilePath(string filePath)
        {
            oldDate = DateTime.Now;
            string tmp_dir = System.AppDomain.CurrentDomain.BaseDirectory + @"log";
            if (Directory.Exists(tmp_dir) == false)//如果不存在就创建file文件夹
            {
                Directory.CreateDirectory(tmp_dir);
            }
            realFilePath = tmp_dir + "\\" + "Pdf2Image" + ".log";
            if (!File.Exists(realFilePath))
            {
                g_fileLog = new FileStream(realFilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read);
            }
            else
            {
                g_fileLog = new FileStream(realFilePath, FileMode.Append, FileAccess.Write, FileShare.Read);
            }
        }

        public void Write(string strLocalLog)
        {
            /*if (DateTime.Now.Day != oldDate.Day)//第二天产生新的日志文件
            {
                g_fileLog.Close();
                FileInfo fi = new FileInfo(realFilePath);
                string newPath = System.AppDomain.CurrentDomain.BaseDirectory + @"log";
                newPath = newPath + "\\" + oldDate.ToString("yyyyMMdd") + @"_" + "NormalService" + ".log";
                try
                {
                    fi.MoveTo(Path.Combine(newPath));
                }
                catch
                {

                }
                SetFilePath("");
            }*/
            byte[] byteLog = Encoding.UTF8.GetBytes(DateTime.Now.ToString("yyyyMMddHHmmss") + " " + strLocalLog + "\r\n");
            g_fileLog.Write(byteLog, 0, byteLog.Length);
            g_fileLog.Flush();
        }
    }
}